package com.ly.demo.service.impl;

import com.ly.demo.entity.SmResult;
import com.ly.demo.service.MyTestService;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @Author liuyang
 * @Date 2024/6/6 下午3:56
 **/
@Service
public class MyTestServiceImpl implements MyTestService {
    @Resource
    private RedisTemplate<String, String> redisTemplate;

    public SmResult pending(HttpServletResponse response) {
        String redisKey = "k1";
        //redisTemplate.opsForValue().set(redisKey, "v1");
        long startTime = System.currentTimeMillis();
        long timeout = 5000; // 5秒

        while (true) {
            if (redisTemplate.hasKey(redisKey)) {
                // 从redis中获取数据
                String redisValue = redisTemplate.opsForValue().get(redisKey);
                response.addCookie(new Cookie("k1","v1"));
                return SmResult.ok(redisValue);
            }

            // 检查是否超过5秒
            if (System.currentTimeMillis() - startTime > timeout) {
                response.setStatus(HttpServletResponse.SC_GATEWAY_TIMEOUT);
                return SmResult.fail(504);
            }

            try {
                // 等待0.5秒
                Thread.sleep(500);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
                return SmResult.fail(504);
            }
        }
    }

}
